<template>
	<div class="container">
		<form class="form-horizontal">
			<div class="form-group">
				<label for="QQ" class="col-xs-3">账号</label>
				<div class="col-xs-8">
					<input type="text" class="form-control" v-model="QQ" name="QQ" id="QQ" />
				</div>
			</div>
			
			<div class="form-group">
				<label for="password" class="col-xs-3">密码</label>
				<div class="col-xs-8">
					<input type="password" class="form-control" v-model="password" name="password" id="password">
				</div>
			</div>
			
			<input type="submit" class="btn btn-info col-xs-4 col-xs-offset-4" @click.prevent="login()" id="login"  value="登录"/>
		</form>
	</div>
	
</template>

<script>
	export default {
		name:'Login',
		data(){
			return {
				QQ:'',
				password:''
			}
		},
		methods:{
			login(){
				const xhr = new XMLHttpRequest()
				xhr.onload = () => {
					if(JSON.parse(xhr.responseText).message){
						alert(JSON.parse(xhr.responseText).message)
					}
					if(JSON.parse(xhr.responseText).account){
						// console.log('账号信息:'+JSON.parse(xhr.responseText).privilegeLevel)
						// const user = {account:this.QQ, pw:this.password, privilegeLevel:this.privilegeLevel}
						// console.log('登录权限'+user.privilegeLevel)
						const user = JSON.parse(xhr.responseText)
						this.$store.commit('setUser',user)
						// this.checkLogin()
						this.$store.commit('setLoginState',true)
						this.$router.push('/Admin/Show')
					}
				}
				xhr.open('POST','/login')
				xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
				xhr.send("QQ="+this.QQ+"&password="+this.password)
			},
			autoLogin(){
				const xhr = new XMLHttpRequest()
				xhr.onload = () => {
					if(JSON.parse(xhr.responseText).message == 'cookie为空'){
						console.log('用户不存在')
						return
					}
					
					const user = JSON.parse(xhr.responseText)
					this.$store.commit('setUser',user)
					this.checkLogin()
					this.$router.push('/Admin/Show')
				}
				xhr.open('post','/autoLogin')
				xhr.send()
			},
			getInfo(){
				const xhr = new XMLHttpRequest()
				xhr.onload = () => {
					console.log(xhr.responseText)
				}
				xhr.open('get','/getAllUserInfo')
				xhr.send()
			},
			checkLogin(){
				this.$store.state.user.account == '' ? this.$store.commit('setLoginState',false)  : this.$store.commit('setLoginState',true)
			}
		},
		created(){
			this.$store.state.user.account == '' ? this.autoLogin() : this.$router.push('/Admin/Show')
		}
	}
</script>

<style scoped="scoped">
	input{
		margin-top: 5px;
	}
	label{
		line-height: 34px;
		text-align: center;
		font-size: 16px;
	}
</style>
